package com.banksoft.cps.service.impl;

import com.banksoft.cps.bean.Company;
import com.banksoft.cps.bean.PoliceCheck;
import com.banksoft.cps.bean.query.PoliceCheckQuery;
import com.banksoft.cps.bean.warpper.PoliceCheckWrapper;
import com.banksoft.cps.dao.CompanyDao;
import com.banksoft.cps.dao.PoliceCheckDao;
import com.banksoft.cps.enums.CheckProcess;
import com.banksoft.cps.service.PoliceCheckService;
import com.banksoft.cps.util.UUIDFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by rongzhao.zhu on 2018/11/14.
 */
@Service
public class PoliceCheckServiceImpl implements PoliceCheckService {
    @Autowired
    PoliceCheckDao policeCheckDao;
    @Autowired
    CompanyDao companyDao;
    @Override
    public List<PoliceCheck> list(PoliceCheckQuery query) {
        return policeCheckDao.list(query);
    }

    @Override
    public List<PoliceCheckWrapper> listWrapper(PoliceCheckQuery query) {
        List<PoliceCheck> policeChecks = policeCheckDao.list(query);
        if(CollectionUtils.isNotEmpty(policeChecks)){
            List<String> companyIdList = policeChecks.stream().map(e->e.getCompanyId()).collect(Collectors.toList());
            List<Company> companies = companyDao.listByIdList(companyIdList);
            Map<String,Company> companyMap = companies.stream().collect(Collectors.toMap(e->e.getId(), e->e));
            return policeChecks.stream().map(e->{
                PoliceCheckWrapper wrapper = new PoliceCheckWrapper();
                BeanUtils.copyProperties(e,wrapper);
                wrapper.setCompany(companyMap.get(e.getCompanyId()));
                return wrapper;
            }).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public long count(PoliceCheckQuery query) {
        return policeCheckDao.count(query);
    }

    @Override
    public PoliceCheck find(String id) {
        return policeCheckDao.findById(id);
    }

    @Override
    public void save(PoliceCheck bean) {
        if(StringUtils.isNotBlank(bean.getId())){
            policeCheckDao.update(bean);
        }else {
            bean.setId(UUIDFactory.random());
            bean.setProcess(CheckProcess.create.name());
            bean.setCreateTime(System.currentTimeMillis());
            policeCheckDao.insert(bean);
        }
    }
}
